<script setup>
import { NCard, NButton, NInput, NFlex,NForm,NFormItem,NIcon,NIconWrapper} from 'naive-ui';
import logo from '../assets/logo.png';
import {ref,computed} from 'vue'
import axiosInstance from '@/utils/axios';
import {Check,X} from "@vicons/tabler"
import { usemsgStore } from '@/stores/msgwrapper';
import { usedialogStore } from '@/stores/dialogwrapper';
import { usecaptchaStore } from '@/stores/captcha'; 

// 验证码状态存储
const  captachaStore = usecaptchaStore()
const {getCaptcha} = captachaStore
const isButtonDisabled = computed(() => captachaStore.isButtonDisabled);
const countdown = computed(() => captachaStore.countdown);
// 对话框状态存储
const dialogStore = usedialogStore();
// 消息状态存储
const msgStore = usemsgStore()
const {sendMessage} = msgStore

// 注册响应式变量
const isRegisterDisabled = ref(false);
//真为可以注册，假为已经注册
const isregistered = ref(false);
const formRef = ref(null)
const formValue = ref({
    username: "",
    password: "",
    ver_code: ""
})
const rule =ref({
      username: {
        required: true,
        trigger: ['input'],
        message:"请填写正确的电话号码",
        validator: (rule, value) => /^1[3-9]\d{9}$/.test(value),
      },
      password: {
        required: true,
        message:"请填写登录密码",
        trigger: ['input'],
      },
      ver_code:{
        required: true,
        trigger: ['input'],
        message:"请填写验证码",
        validator: (rule, value) => value.trim() !== "" && value.length > 0,
      }
    },)

// 检查该电话号码是否注册过
const checkPhoneRegistered = async () => {
    const username = formValue.value.username;
    // 正则表达式，用于匹配中国大陆的手机号码
    const phoneRegex = /^1[3-9]\d{9}$/;
        if (!username || !phoneRegex.test(username)) {
            isregistered.value = false; 
            return;
        }

        try {
            const res = await axiosInstance.get('/api/check', { params: { username } });
            if (res.data.success && res.data.code === 200) {
                isregistered.value = true;
            } 
            else 
            {
                isregistered.value = false;
                sendMessage("error","该号码已经注册过")
            }
        } catch (error) {
            isregistered.value = false; 
            sendMessage("error","检查电话号码状态失败，请稍后再试");
        }
};

//注册函数
const handleRegister = async (e) => {
  e.preventDefault();
  isRegisterDisabled.value = true;
  try {
    await formRef.value?.validate();
    // 表单验证通过，执行登录请求
    const username = formValue.value.username;
    const password = formValue.value.password;
    const ver_code = formValue.value.ver_code
    sendMessage("loading",'正在检验注册进程', {
      duration: 1000,
      onAfterLeave: async () => {
        try {
          const res = await axiosInstance.post('/api/register', { username, password,ver_code });
          if (res.data.success && res.data.code === 200) {
            dialogStore.closeDialog()
            sendMessage("success","注册成功", {
              duration: 500,
            });
          } else {
            sendMessage("error",res.data.message);
          }
        } catch (error) {
          sendMessage("error","注册请求失败，请稍后再试。");
        } finally {
          formValue.value.password = "";
          isRegisterDisabled.value = false
        }
      }
    });
  } catch (errors) {
    // 处理表单验证错误
    sendMessage("error","请完整正确填写信息");
    isRegisterDisabled.value = false;
  }
};

</script>

<template>
    <n-card class="up">
        <img :src="logo" width="200px" style="margin-left: 160px; margin-top: -20px" height="150px">
    </n-card>
    <n-card class="down">
                <span style="font-weight: bold; font-size: 16px; margin-left: 225px">手机注册</span>
        <n-flex>
            <n-form ref="formRef" :model="formValue" :rules="rule">
            <n-flex column>
                <n-form-item path="username" feedback-style="margin-left:180px;">
                    <n-input v-model:value="formValue.username" placeholder="手机号" maxlength="11" style="margin-top:-30px; height: 52.6px; width:326px; font-size: 16px; line-height: 52.6px; margin-left: 100px" @blur="checkPhoneRegistered">
                        <template #suffix v-if="isregistered == false">
                            <n-icon-wrapper color="red">
                                <n-icon :component="X"/>
                            </n-icon-wrapper>
                        </template>
                        <template #suffix v-else>
                            <n-icon-wrapper color="green">
                                <n-icon :component="Check"/>
                            </n-icon-wrapper>
                        </template>
                    </n-input>

                </n-form-item>
                <n-form-item path="password" feedback-style="margin-left:180px;margin-top: -10px;">
                    <n-input v-model:value="formValue.password" placeholder="密码" style="height: 52.6px; width:326px; font-size: 16px; line-height: 52.6px; margin-top:-50px;margin-left: 100px"></n-input>
                </n-form-item>
                <n-flex gap="10px" style="margin-top:15px;">
                    <n-form-item path="ver_code" feedback-style="margin-left:210px;margin-top: -30px;">
                        <n-input v-model:value="formValue.ver_code" placeholder="请输入验证码" style="height: 52.6px; width:230px; font-size: 16px; line-height: 52.6px;margin-left: 100px;margin-top: -80px"></n-input>
                    </n-form-item>
                    <n-button
                        :disabled="isButtonDisabled"
                        type="primary"
                        style="height: 52.6px; width:100px; background-color: cornflowerblue;margin-top: -40px; margin-top: -23px;"
                        @click="getCaptcha(formValue.username)"
                    >
                        {{ countdown > 0 ? `重新发送(${countdown})` : '获取验证码' }}
                    </n-button>
                </n-flex>
            </n-flex>
            <n-button style="height: 52.6px; width:326px;margin-left: 100px" type="info" @click="handleRegister" :disabled="isRegisterDisabled">注册</n-button>
        </n-form>
        </n-flex>
    </n-card>
</template>

<style>
.up {
    border-top-left-radius: 25px;
    border-top-right-radius: 25px;
    border: 2px solid whitesmoke;
    width: 604px;
    height: 140px;
    margin-left: -28px;
    margin-top: -30px;
    background-color: #DBEDFF;
}

.down {
    padding: 23px 40px 32px 0px;
    background-color: white;
    width: 602.9px;
    height: 408px;
    border: 2px solid whitesmoke;
    margin-left: -27px;
    border-bottom-left-radius: 25px;
    border-bottom-right-radius: 25px;
}
</style>